<template>
  <div>
    <el-page-header @back="goBack" :content="$route.query.id ? '编辑指标' : '新建指标'"> </el-page-header>

    <div class="ueba-detail-main">
      <sec-form
        ref="formData"
        :span="8"
        :ruleForm="formData.data"
        :rules="formData.rules"
        :disabledProp="formData.disabledProp"
        :formValidateData="formData.config"
        :optionData="optionData"
        :hideProp="formData.hideProp"
      >
        <template v-slot:scoreRule>
          <el-form-item label="执行情况">
            <el-row>
              <el-col :span="8">
                <el-form-item label="是" prop="busAccordScore">
                  <el-input v-model="formData.data.busAccordScore" @input="handleInput('busAccordScore')">
                    <template slot="append">分</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="否" prop="busNonaccordScore">
                  <el-input v-model="formData.data.busNonaccordScore" @input="handleInput('busNonaccordScore')">
                    <template slot="append">分</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="审计结果">
            <el-row>
              <el-col :span="8">
                <el-form-item label="符合" prop="auditAccordScore">
                  <el-input v-model="formData.data.auditAccordScore" @input="handleInput('auditAccordScore')">
                    <template slot="append">分</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="不符合" prop="auditNonaccordScore">
                  <el-input v-model="formData.data.auditNonaccordScore" @input="handleInput('auditNonaccordScore')">
                    <template slot="append">分</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <template v-slot:ruleList>
          <el-empty description="暂无审计信息" v-if="!ruleList || ruleList.length == 0"></el-empty>
          <el-collapse v-model="activeNames" v-else>
            <el-collapse-item
              :title="item.ruleName"
              :name="item.ruleName"
              v-for="(item, index) in ruleList"
              :key="index"
            >
              <secTable
                :tableData="item.remark"
                :tableCol="ruleListTableCol"
                :optionData="ruleListOptionData"
              ></secTable>
            </el-collapse-item>
          </el-collapse>
        </template>
        <template v-slot:repaireDay>
          <div style="text-align: left">
            <el-input
              type="number"
              style="width: 50%; text-align: left"
              v-model="formData.data.repaireDay"
              placeholder="请输入正整数"
              oninput="value=value.replace(/[^\d]/g,'')"
            ></el-input>
            <span style="margin-left: 5px; color: #606266">天以内</span>
          </div>
        </template>
      </sec-form>
    </div>
  </div>
</template>

<script>
import secTable from "components/table/comTable.vue";
import { getAutoPreConditionsApi } from "api/configApi";
export default {
  components: {
    secTable,
  },
  props: {},
  data() {
    return {
      ruleList: [],
      activeNames: [],
      ruleListOptionData: {
        status: [
          { label: "符合", value: "0" },
          { label: "不符合", value: "1" },
          { label: "待确定", value: "2" },
        ],
      },
      ruleListTableCol: [
        { label: "状态", prop: "status", type: "select", disabled: true },
        { label: "现状描述", prop: "remark", type: "text" },
      ],
      optionData: {
        pmAccount: [],
        noticeUsers: [],
        leader: [],
        autoPreConditions: [],
      },
      scoreId: "",
      formData: {
        disabledProp: {
          strategyType: false,
          manual: false,
          autoAnquan: false,
        },
        hideProp: {
          evidence: true,
          scoreRule: true,
          autoPreConditions: true,
          scoreTitle: true,
        },
        data: {
          autoPreConditions: [],
          name: "",
          scene: "",
          required: "",
          auto: "",
          weight: "",
          enable: "",
          reportItemContent: "",
          remark: "",
          busAccordScore: "",
          busNonaccordScore: "",
          auditAccordScore: "",
          auditNonaccordScore: "",
          ruleList: [], //审计信息
          holeName: "",
          holeType: "",
          riskLevel: "",
          holeDetail: "",
          repairRecommend: "",
          evidence: 0,
          manual: 0,
          autoAnquan: 0,
          strategyType: 0,
          repaireDay: "60",
        },

        config: [
          { title: "基础信息" },
          {
            type: "text",
            label: "指标名称",
            prop: "name",
          },
          {
            type: "select",
            clearable: true,
            filterable: true,
            label: "指标来源",
            prop: "scene",
            multiple: true,
            option: this.$store.state.dictionary[101003],
            change: () => {
              this.scoreRuleHandle(); //根据指标是子系统权限的，展示计分规则
            },
          },
          {
            type: "select",
            clearable: true,
            filterable: false,
            label: "是否必须",
            prop: "required",

            option: this.$store.state.dictionary["whetherNum"],
          },
          {
            type: "select",
            clearable: true,
            filterable: false,
            label: "是否自动化",
            prop: "auto",
            span: 6,
            change: () => {
              this.autoDisabled();
            },
            option: this.$store.state.dictionary["whetherNum"],
          },
          {
            type: "select",
            multiple: true,
            clearable: true,
            filterable: false,
            label: "自动化前置条件",
            prop: "autoPreConditions",
            collapseTags: true,
            optionProps: { label: "message", value: "code" },
            span: 6,
          },

          { type: "text", label: "指标权重", prop: "weight", span: 6 },
          {
            type: "select",
            clearable: true,
            filterable: true,
            label: "是否启用",
            prop: "enable",
            span: 6,
            option: this.$store.state.dictionary["whetherNum"],
          },
          //todo
          {
            type: "radio",
            label: "策略类型",
            prop: "strategyType",
            span: 6,
            optionData: this.$store.state.dictionary["strategyType"],
          },
          {
            type: "radio",
            label: "是否人工辅助",
            prop: "manual",
            span: 6,
            optionData: this.$store.state.dictionary["whetherNum"],
          },
          {
            type: "radio",
            label: "是否自动发工单",
            prop: "autoAnquan",
            span: 6,
            optionData: this.$store.state.dictionary["whetherNum"],
          },
          {
            type: "radio",
            label: "证据是否必传",
            prop: "evidence",
            span: 6,
            optionData: this.$store.state.dictionary["whetherNum"],
          },
          //todo
          { type: "textarea", span: 24, label: "指标依据", prop: "basis" },
          { type: "textarea", span: 24, label: "指标要求", prop: "reportItemContent" },
          { type: "textarea", span: 24, label: "备注", prop: "remark" },
          { type: "textarea", span: 24, label: "审计标准", prop: "auditStandard" },
          { title: "记分规则", prop: "scoreTitle" },
          { type: "slot", span: 24, class: "scoreRule", prop: "scoreRule" },
          { title: "审计信息" },
          { type: "slot", prop: "ruleList", span: 24, style: { align: "left" } },
          { title: "风险信息" },
          { type: "text", span: 8, label: "风险名称", prop: "holeName" },
          {
            type: "select",
            span: 8,
            label: "风险类型",
            prop: "holeType",
            clearable: true,
            filterable: true,
            option: this.$store.state.dictionary[101002],
          },
          {
            type: "select",
            span: 8,
            label: "风险等级",
            prop: "riskLevel",
            clearable: true,
            filterable: true,
            option: this.$store.state.dictionary["level"],
          },
          { type: "slot", label: "修复期限", prop: "repaireDay", span: 24 },
          { type: "textarea", span: 24, label: "风险描述", prop: "holeDetail" },
          { type: "textarea", span: 24, label: "修复建议", prop: "repairRecommend", maxlength: "max" },

          {
            type: "operation",
            span: 24,
            style: { "text-align": "center" },
            children: [
              {
                label: "保 存",
                type: "primary",
                click: () => {
                  //if中是验证表单有没有通过，不是提交数据
                  if (this.$refs.formData.submitForm()) {
                    //这里是提交数据
                    this.submitForm();
                  }
                },
              },
            ],
          },
        ],
        rules: {
          name: [
            { required: true, message: "请输入指标名称", trigger: "blur" },
            //{ min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
          ],
          scene: [{ required: true, message: "请输入指标来源", trigger: "blur" }],
          required: [{ required: true, message: "请输入是否必须", trigger: "blur" }],
          auto: [{ required: true, message: "请输入是否自动化", trigger: "blur" }],
          weight: [{ required: true, message: "请输入指标权重", trigger: "blur" }],
          enable: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
          evidence: [{ required: true, message: "请输入证据是否必传", trigger: "blur" }],
          reportItemContent: [{ required: true, message: "请输入指标要求", trigger: "blur" }],
          busAccordScore: [{ required: true, message: "请输入执行情况", trigger: "blur" }],
          busNonaccordScore: [{ required: true, message: "请输入执行情况", trigger: "blur" }],
          auditAccordScore: [{ required: true, message: "请输入审计结果", trigger: "blur" }],
          auditNonaccordScore: [{ required: true, message: "请输入审计结果", trigger: "blur" }],
          holeName: [{ required: true, message: "请输入风险名称", trigger: "blur" }],
          holeType: [{ required: true, message: "请输入风险类型", trigger: "blur" }],
          riskLevel: [{ required: true, message: "请输入风险等级", trigger: "blur" }],
          repaireDay: [{ required: true, message: "请输入正整数", trigger: "blur" }],
        },
      },
    };
  },
  async mounted() {
    await getAutoPreConditionsApi().then((res) => {
      this.optionData.autoPreConditions = res.data || [];
    });
    if (this.$route.query.id) {
      // edit
      let temp = await this.fatchData(this.$route.query.id);
      temp.autoPreConditions = temp.autoPreConditions ? temp.autoPreConditions.split(",") : [];
      temp.riskLevel = temp.riskLevel && temp.riskLevel.toString();
      temp.evidence = temp.evidence ? 1 : 0;
      if (temp.itemScore) {
        this.scoreId = temp.itemScore.id;
        this.formData.data.busNonaccordScore = temp.itemScore.busNonaccordScore;
        this.formData.data.busAccordScore = temp.itemScore.busAccordScore;
        this.formData.data.auditAccordScore = temp.itemScore.auditAccordScore;
        this.formData.data.auditNonaccordScore = temp.itemScore.auditNonaccordScore;
      }

      this.formData.data = { ...this.formData.data, ...temp };
      console.log("[ this.formData ] >", this.formData.data);
      this.ruleList = temp.ruleList;
      this.scoreRuleHandle(); //根据指标是子系统权限的，展示计分规则
      this.autoDisabled(); //是否自动化 失效关联

      this.ruleList?.forEach((item) => {
        this.activeNames.push(item.ruleName);
        item.remark = item.remark ? JSON.parse(item.remark) : [];
        if (typeof item.remark === "string") {
          item.remark = JSON.parse(item.remark);
        }
      });
      console.log("[ this.ruleList ] >", this.ruleList);
    }
  },
  methods: {
    scoreRuleHandle() {
      if (this.formData.data.scene.includes("subsystemperm")) {
        this.formData.hideProp.evidence = false;
        this.formData.hideProp.scoreRule = false;
        this.formData.hideProp.scoreTitle = false;
      } else {
        this.formData.hideProp.evidence = true;
        this.formData.hideProp.scoreRule = true;
        this.formData.hideProp.scoreTitle = true;
      }
    },
    handleInput(value) {
      this.formData.data[value] = this.formData.data[value].toString().replace(/[^\d]/g, "");
    },
    autoDisabled() {
      for (let key in this.formData.disabledProp) {
        this.formData.disabledProp[key] = !this.formData.data.auto;
      }
    },
    addEvalRule() {
      let obj = { ruleName: "", remark: "" };
      this.formData.data.evalInfo.push(obj);
    },
    goBack() {
      this.$router.push("/config/index");
    },
    async submitForm() {
      let { ruleList } = this.formData.data;
      this.formData.data.ruleList =
        ruleList?.map((item) => {
          let remark = item.remark ? JSON.stringify(item.remark) : JSON.stringify([]);
          return { id: item.id, remark: remark };
        }) || [];
      let loading = this.openLoading();
      console.log(this.formData.data);
      let params = Object.assign({}, this.formData.data);
      params.itemScore = {
        busAccordScore: this.formData.data.busAccordScore,
        busNonaccordScore: this.formData.data.busNonaccordScore,
        auditAccordScore: this.formData.data.auditAccordScore,
        auditNonaccordScore: this.formData.data.auditNonaccordScore,
        id: this.scoreId,
      };
      delete params.busAccordScore;
      delete params.busNonaccordScore;
      delete params.auditAccordScore;
      delete params.auditNonaccordScore;
      //深复制一下
      let autoPreConditions = JSON.parse(JSON.stringify(params.autoPreConditions));
      params.autoPreConditions = autoPreConditions?.join(",");
      // console.log("[ params ] >", params);
      if (typeof params.repaireDay === "string") {
        params.repaireDay = Number(params.repaireDay);
      }
      let res = await this.$store.dispatch("config/itemUpdate", params);
      loading.close();
      if (res.code == 0) {
        this.message.state(res);
        this.goBack();
      }
    },

    async fatchData(id) {
      let res = await this.$store.dispatch("config/itemGet", { id: id });
      return res.data;
    },
  },
  computed: {},
  watch: {
    "formData.data.auto": {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.formData.hideProp.autoPreConditions = newVal === 1 ? false : true;
      },
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .scoreRule .el-form-item__content {
  margin-left: 0 !important;
  display: grid;
}
.check-box {
  margin: 0 0 20px 20px;
}
</style>
